﻿#include "webview.h"
#include <QFile>
#include <QMessageBox>
#include <QJsonObject>
#include <QJsonDocument>
#include <QWebChannel>
#include<QSqlQuery>

extern QString gHeadPicture;
extern int ReceiverAccount;
msgHtmlObj::msgHtmlObj(QObject*parent):QObject(parent){
    initHtml();
}

webView::webView(QWidget *parent)
    : QWebEngineView(parent),m_channel(new QWebChannel(this))
{

    m_msgHtmlObj = new msgHtmlObj(this);
    m_channel->registerObject("external0", m_msgHtmlObj);
    msgHtmlObj*obj=new msgHtmlObj(this);
    m_channel->registerObject(QString("external_%1").arg(QString::number(ReceiverAccount)), obj);
    this->page()->setWebChannel(m_channel);
    this->load(QUrl("qrc:/src/msgTmpl.html"));//初始化收信息页面
}

webView::~webView()
{
}

void webView::appendMsg(const QString & html,QString obj)
{
    QJsonObject msgObj;
    msgObj.insert("MSG", html);//以键值对的方式插入,(key,value)
    const QString &Msg=QJsonDocument(msgObj).toJson(QJsonDocument::Compact);//转换成utf-8格式,紧凑模式,现在就是一个字符串了
    if (obj == "0") {//发信息  external0
        this->page()->runJavaScript(QString("appendHtml0(%1)").arg(Msg));

    }
    else {//收信息
        this->page()->runJavaScript(QString("recvHtml_%1(%2)").arg(obj).arg(Msg));
    }
}


void msgHtmlObj::initHtml()
{
    QSqlQuery query(QString("select picture from info where account=%1").arg(ReceiverAccount));
    query.first();
    m_msgLHtml = getMsgHtml("msgleftTmpl");
    m_msgLHtml.replace("%1", "qrc"+query.value(0).toString());
    m_msgRHtml = getMsgHtml("msgrightTmpl");
    m_msgRHtml.replace("%1", "qrc"+gHeadPicture);
}

QString msgHtmlObj::getMsgHtml(const QString & code)
{
    QFile file(":/src/" + code + ".html");
    QString str = "";
    if (file.open(QFile::ReadOnly)) {
        str = QLatin1String(file.readAll());
        file.close();
    }
    else {
        QMessageBox::warning(nullptr, "error!", "init html fail!");
    }
    return str;
}

